package com.codedancer.campus.client.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.codedancer.campus.client.service.ICaptchaService;
import com.codedancer.campus.client.service.vo.captcha.CaptchaVo;
import com.codedancer.campus.common.utils.RedisUtil;
import com.codedancer.campus.common.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CaptchaServiceImpl implements ICaptchaService {

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 存放验证码RedisKey
     */
    @Value("${start.campus.redis.captcha.key}")
    private  String CAPTCHA_KEY;

    /**
     * 生成验证码
     * @return
     */
    @Override
    public CaptchaVo generate() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,4,2);
        //生成验证码
        lineCaptcha.createCode();
        //新的验证码的值
        String captchaCode = lineCaptcha.getCode();
        // 创建uuid存入redis
        String captchaKey = UUIDGenerator.getUUID();
        log.info("验证码Key：{}，验证码值：{}",captchaKey,captchaCode);
        redisUtil.setStringValueAndTime( CAPTCHA_KEY + captchaKey, captchaCode, (long) 300);
        // 获取验证码图片的base64
        String captchaImage = lineCaptcha.getImageBase64();
        return CaptchaVo.builder()
            .captchaKey(captchaKey)
            .captchaImage(captchaImage).build();
    }
}
